package com.example.yk2021xm04.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yk2021xm04.pojo.Task;
import com.example.yk2021xm04.mapper.TaskMapper;
import com.example.yk2021xm04.pojo.User;
import com.example.yk2021xm04.query.TaskQuery;
import com.example.yk2021xm04.service.ITaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yk2021xm04.utils.AssertUtil;
import com.example.yk2021xm04.utils.PageResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiYongle
 * @since 2021-12-02
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addTask(Task task) {
        /**
         * 任务名
         * 非空 不可重复
         * 任务默认有效
         */
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User) principal;
        AssertUtil.isTrue(StringUtils.isBlank(task.getTaskName()),"任务名不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(task.getTaskUserName()),"任务人不能为空");
        task.setPublishTime(LocalDateTime.now());
        task.setPublishName(user.getTrueName());
        task.setPublishId(user.getId());
        List<Object> temp = this.baseMapper.getUserByName(task.getTaskUserName());

        AssertUtil.isTrue(temp.isEmpty(),"任务人不存在");
        AssertUtil.isTrue(!(this.save(task)),"任务记录添加失败");
    }

    @Override
    public Map<String, Object> taskList(Integer userId,TaskQuery taskQuery) {
        //分页的类
        IPage<Task> page = new Page<Task>(taskQuery.getPage(), taskQuery.getLimit());
        //QueryWrapper：sql条件查询
        //eq("is_del", 0) 代表 where is_del=0
        //详细可搜索相关用法
        QueryWrapper<Task> queryWrapper = new QueryWrapper<Task>();
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User) principal;
        queryWrapper.eq("task_user_name",user.getTrueName()).or().eq("publish_name",user.getTrueName());

        //这里就是代表 sql语句中的 like
        if(StringUtils.isNotBlank(taskQuery.getTaskName())) {
            queryWrapper.like("task_name",taskQuery.getTaskName());
        }
        //已经写好的接口
        page = this.baseMapper.selectPage(page,queryWrapper);
        System.out.println(page.getTotal());
        return PageResultUtil.getResult(page.getTotal(),page.getRecords());
    }

    @Override
    public void deleteTask(Integer[] ids) {
        /**
         * 批量删除任务
         */
        AssertUtil.isTrue(null==ids || ids.length==0,"请选择待删除的id");

        /**
         * 第一种删除，只设置IsDel值为1，不从数据库中删除
         */
//        List<Task> tasks = new ArrayList<>();
//        for (Integer id : ids) {
//            Task temp = this.getById(id);
//            temp.setIsDel(1);
//            tasks.add(temp);
//        }
//        AssertUtil.isTrue(!(this.updateBatchById(tasks)),"任务记录删除失败");
        /**
         * 第二种删除，直接从数据库删除
         * 先采用这一种
         */
        AssertUtil.isTrue(!(this.removeByIds(Arrays.asList(ids))),"任务记录删除失败");
    }

    @Override
    public void updateTask(Task task) {
        /**
         * 任务名
         * 非空 不可重复
         */
        AssertUtil.isTrue(StringUtils.isBlank(task.getTaskName()),"任务名不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(task.getTaskUserName()),"任务人不能为空");
        Task temp = this.findTaskByTaskName(task.getTaskName());
        AssertUtil.isTrue(null!=temp&&!(temp.getId().equals(task.getId())),"任务名已存在！");
        List<Object> temp0 = this.baseMapper.getUserByName(task.getTaskUserName());

        AssertUtil.isTrue(temp0.isEmpty(),"任务人不存在");
        AssertUtil.isTrue(!(this.updateById(task)),"任务记录更新失败");
    }

    private Task findTaskByTaskName(String taskName) {
        return this.baseMapper.selectOne(new QueryWrapper<Task>().eq("task_name",taskName));
    }

    @Override
    public List<Object> publishTimeByDay() {
        return this.baseMapper.publishTimeByDay();
    }

    @Override
    public List<Object> publishCountByDay() {
        return this.baseMapper.publishCountByDay();
    }

    @Override
    public Integer TaskCountInDay() {
        return this.baseMapper.TaskCountInDay();
    }

    @Override
    public Integer TaskCountInYesterday() {
        return this.baseMapper.TaskCountInYesterday();
    }

}
